package com.funsport.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 天气查询工具类
 * 集成第三方天气API（如：和风天气、高德天气等）
 *
 * @author Fun-Sport Team
 */
@Slf4j
@Component
public class WeatherUtil {

    @Value("${weather.api.key:}")
    private String weatherApiKey;

    @Value("${weather.api.url:https://devapi.qweather.com}")
    private String weatherApiUrl;

    private final RestTemplate restTemplate = new RestTemplate();
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 查询城市天气信息
     *
     * @param city 城市名称
     * @return 天气信息，失败返回null
     */
    public Map<String, Object> getWeather(String city) {
        // TODO: 实际项目中需要配置真实的天气API
        // 这里提供一个模拟示例

        // 模拟天气数据
        Map<String, Object> mockWeather = new HashMap<>();
        mockWeather.put("city", city);
        mockWeather.put("temperature", 25);
        mockWeather.put("weather", "晴");
        mockWeather.put("humidity", 60);
        mockWeather.put("wind", "东南风3级");
        mockWeather.put("aqi", 50);
        mockWeather.put("airQuality", "优");
        mockWeather.put("tips", "天气晴朗，适合户外运动");

        List<Map<String, Object>> forecast = new ArrayList<>();
        forecast.add(createForecast("今天", "晴", 18, 28));
        forecast.add(createForecast("明天", "多云", 20, 30));
        forecast.add(createForecast("后天", "阴", 19, 27));
        mockWeather.put("forecast", forecast);

        mockWeather.put("updateTime", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

        log.info("获取天气信息: city={}, weather={}", city, mockWeather.get("weather"));
        return mockWeather;

        /* 以下是使用和风天气API的示例代码（需要真实API Key）
        
        if (weatherApiKey == null || weatherApiKey.isEmpty()) {
            log.warn("天气API密钥未配置，返回模拟数据");
            return mockWeather;
        }

        try {
            String url = weatherApiUrl + "/v7/weather/now?location=" + city + "&key=" + weatherApiKey;
            String response = restTemplate.getForObject(url, String.class);
            
            Map<String, Object> data = objectMapper.readValue(response, Map.class);
            
            if ("200".equals(data.get("code"))) {
                Map<String, Object> now = (Map<String, Object>) data.get("now");
                
                Map<String, Object> result = new HashMap<>();
                result.put("city", city);
                result.put("temperature", Integer.parseInt(now.get("temp").toString()));
                result.put("weather", now.get("text"));
                result.put("humidity", Integer.parseInt(now.get("humidity").toString()));
                result.put("wind", now.get("windDir") + " " + now.get("windScale") + "级");
                result.put("updateTime", now.get("obsTime"));
                
                return result;
            } else {
                log.error("查询天气失败: {}", data);
                return null;
            }
        } catch (Exception e) {
            log.error("查询天气异常: {}", e.getMessage());
            return null;
        }
        */
    }

    /**
     * 创建天气预报数据
     */
    private Map<String, Object> createForecast(String date, String weather, int tempLow, int tempHigh) {
        Map<String, Object> forecast = new HashMap<>();
        forecast.put("date", date);
        forecast.put("weather", weather);
        forecast.put("tempLow", tempLow);
        forecast.put("tempHigh", tempHigh);
        return forecast;
    }

    /**
     * 检查天气是否适合运动
     *
     * @param city 城市名称
     * @param sportType 运动类型（outdoor/indoor）
     * @return 适合度评估结果
     */
    public Map<String, Object> checkWeatherSuitableForSport(String city, String sportType) {
        Map<String, Object> weather = getWeather(city);

        if (weather == null) {
            Map<String, Object> result = new HashMap<>();
            result.put("suitable", true);
            result.put("level", "unknown");
            result.put("reason", "无法获取天气信息");
            return result;
        }

        // 室内运动不受天气影响
        if ("indoor".equalsIgnoreCase(sportType)) {
            Map<String, Object> result = new HashMap<>();
            result.put("suitable", true);
            result.put("level", "good");
            result.put("reason", "室内运动不受天气影响");
            return result;
        }

        // 户外运动天气判断
        int temp = (Integer) weather.get("temperature");
        String weatherText = (String) weather.get("weather");
        int aqi = (Integer) weather.get("aqi");

        // 极端天气
        String[] badWeather = {"雨", "雪", "雷", "暴", "冰雹", "台风"};
        for (String bad : badWeather) {
            if (weatherText.contains(bad)) {
                Map<String, Object> result = new HashMap<>();
                result.put("suitable", false);
                result.put("level", "bad");
                result.put("reason", String.format("当前天气%s，不适合户外运动", weatherText));
                return result;
            }
        }

        // 空气质量差
        if (aqi > 150) {
            Map<String, Object> result = new HashMap<>();
            result.put("suitable", false);
            result.put("level", "bad");
            result.put("reason", String.format("空气质量较差（AQI: %d），不建议户外运动", aqi));
            return result;
        }

        // 温度过高或过低
        if (temp > 35 || temp < 0) {
            Map<String, Object> result = new HashMap<>();
            result.put("suitable", false);
            result.put("level", "caution");
            result.put("reason", String.format("温度%d°C，建议谨慎选择户外运动时间", temp));
            return result;
        }

        // 良好天气
        Map<String, Object> result = new HashMap<>();
        result.put("suitable", true);
        result.put("level", "good");
        result.put("reason", String.format("天气%s，温度%d°C，适合户外运动", weatherText, temp));
        result.put("weather", weather);
        return result;
    }

    /**
     * 根据天气文本返回对应的图标emoji
     *
     * @param weatherText 天气描述文本
     * @return 图标标识
     */
    public String getWeatherIcon(String weatherText) {
        Map<String, String> weatherIcons = new HashMap<>();
        weatherIcons.put("晴", "☀️");
        weatherIcons.put("多云", "⛅");
        weatherIcons.put("阴", "☁️");
        weatherIcons.put("雨", "🌧️");
        weatherIcons.put("雪", "❄️");
        weatherIcons.put("雷", "⛈️");
        weatherIcons.put("雾", "🌫️");
        weatherIcons.put("霾", "😷");

        for (Map.Entry<String, String> entry : weatherIcons.entrySet()) {
            if (weatherText.contains(entry.getKey())) {
                return entry.getValue();
            }
        }

        return "🌤️";
    }

    /**
     * 根据天气给出运动时间建议
     *
     * @param city 城市名称
     * @param sportType 运动类型
     * @return 时间建议
     */
    public Map<String, Object> getSportTimeSuggestion(String city, String sportType) {
        // TODO: 结合天气预报给出具体时间建议

        Map<String, Object> suggestions = new HashMap<>();

        Map<String, Object> morning = new HashMap<>();
        morning.put("time", "06:00-08:00");
        morning.put("suitable", true);
        morning.put("reason", "早晨空气清新，适合晨练");

        Map<String, Object> afternoon = new HashMap<>();
        afternoon.put("time", "15:00-17:00");
        afternoon.put("suitable", true);
        afternoon.put("reason", "下午气温适宜");

        Map<String, Object> evening = new HashMap<>();
        evening.put("time", "18:00-20:00");
        evening.put("suitable", true);
        evening.put("reason", "傍晚凉爽舒适");

        suggestions.put("morning", morning);
        suggestions.put("afternoon", afternoon);
        suggestions.put("evening", evening);

        Map<String, Object> result = new HashMap<>();
        result.put("city", city);
        result.put("sportType", sportType);
        result.put("suggestions", suggestions);
        result.put("bestTime", "18:00-20:00");

        return result;
    }
}

